import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FormValidatorService } from 'great-ngform';

@Component({
  selector: 'app-table-table-tree-from',
  templateUrl: './form.component.html'
})
export class TableTableTreeFormComponent implements OnInit {
  form: FormGroup;
  // @ts-ignore
  @Input() parentNode;
  // @ts-ignore
  @Input() node;

  constructor(private fb: FormBuilder, private formValidatorService: FormValidatorService) {
    this.form = this.fb.group({
      parentKey: [null, []],
      key: [null, []],
      name: [null, [Validators.required]],
      num: ['0', [Validators.required]],
      address: ['1', []]
    });
  }

  ngOnInit(): void {
    if (this.parentNode) {
      this.form.patchValue({
        parentKey: this.parentNode.key,
        key: Math.random()
      });
    }
    if (this.node) {
      this.form.patchValue(this.node);
    }
  }

  submitForm(): any {
    Object.keys(this.form.controls).forEach(key => {
      const valid = this.form.controls[key].valid;
      if (!valid) {
        console.log(this.form.controls[key]);
      }
      console.log(key, '-->', valid);
    });
    this.formValidatorService.checkForm(this.form);
    if (this.form.valid) {
      return this.form.value;
    } else {
      return null;
    }
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.form.reset();
    this.formValidatorService.checkForm(this.form);
  }
}
